// components/good-list/good-list.js
let app = getApp()
const moment = require('../../utils/moment.min.js')
Component({

  options: {
    addGlobalClass: true,//使用app.wxss样式
    styleIsolation: 'shared'
  },
  /**
   * 组件的属性列表
   */
  properties: {
    type: String,
    keyword: String,//搜索值
    express: String,// 1 快递直发
    ismiaosha: String,// 1 秒杀
    isYushou:String,//1 预售
    isHot:String,//1 爆款
    isYuyue:String,//预约
    isSpellgroup: String,//1 拼团商品
    isTeam: String,
    isStationmasterTo: {//商户商品标识
      type: Boolean,
      observer (newVal, oldVal, changedPath) {
        this.setData({isStationmaster: newVal})
      }
    },
    // 条件筛选
    sidx:String,//排序字段，存储选择的是价格还是销量还是最新
    order:String,//升降序
    minPrice:String,//最小价格
    maxPrice:String//最大价格
  },

  /**
   * 组件的初始数据
   */
  data: {
    goodsList: [],
    currPage: 1,
    perPage: 4,
    noMore: false,//false 还有更多数据，true 到底了
    listIndex: '',
    screenWidth: '',
    screenHeight: '',
    isEmpty: false,//true  无数据
    globalConfig: app.getGlobalConfig(),
    isShowShare: false,//控制分享组件

    serverTime: Date.now(),
    timeover: '',//商品是否结束
    timestart: '',//商品是否开始买卖

    isStationmaster: false,//商户商品标识
    thenGoodsId: '',//分享组件需要使用goodsId查询数据

    showLogin: false,//登录弹框

    showSku: false,//规格弹框
    skuGoods: {
      id: '',
      detail: '',
      selectSku: '',//选中的规格
      selectNum: 1,//规格数量
    },
    productType:'',//0:普通 1预售 2拼团 3秒杀 4预约 5积分兑换，只有1234传值，其他为空
    playing: false,//视频是否在播放
  },

  lifetimes: {
    ready () {
      this.getHeight()
    },

  },

  /**
   * 组件的方法列表
   */
  methods: {
    //分享
    shareClick (event) {
      let user = app.getUser();
      if(user.id == null){
        this.setData({ showLogin: true })
        return;
      }

      let sd = {
        id: event.currentTarget.dataset.goodsid,
        thumb: event.currentTarget.dataset.thumb,
        title: event.currentTarget.dataset.title
      };
      this.triggerEvent('shareGoodsIdSuffer', sd);//将分享需要数据传给页面使用
      this.setData({
        isShowShare: true,
        thenGoodsId: event.currentTarget.dataset.goodsid,
      })
    },
    //接收分享
    isShowShareSuffer (event) {
      this.setData({
        isShowShare: event.detail,
      })
    },

    //加入购物车
    addCart (event) {
      let _this = this
      let user = app.getUser();

      if(user.id == null){
        this.setData({ showLogin: true })
        return;
      }

      let goods = event.currentTarget.dataset['goods']
      let plus = event.currentTarget.dataset['plus']
      let skuData = event.currentTarget.dataset['skuData']

      if(goods.isTeamBuy==1 && user.isteam!==3){
        wx.showToast({
          title: '抱歉，只有团长才能购买此商品！',
          icon: 'none'
        })
        return;
      }

      if(goods.hasoption == 1 && (!_this.data.showSku || goods.id != _this.data.skuGoods.id)) {//多规格商品
        if(!_this.data.skuGoods || goods.id != _this.data.skuGoods.id){
          app.requestUrl({
            method: 'GET',
            url: '/wxapi/shop/products/detail',
            data: {
              productId: goods.id,
              memberId: user.id
            }
          }).then(res =>{
            _this.setData({
              skuGoods: goods,
              ['skuGoods.detail']: res.data.data,
              showSku: true,
            })
          })
        } else {
          _this.setData({  showSku: true })
        }
      } else {//加入购物车，包含多规格加入购物车
        //普通
        let cartItem = {
          mid: user.id ? user.id : '',
          centreId: app.globalData.loginCentreId,
          teamId: user.upshopTid ? user.upshopTid : '',//未登录需要传门店id
          openid: user.openid ? user.openid : '',
          productId: goods.id,
          total: plus ? 1 : -1,//plus=true加入购物车，plus=false减
          marketprice: (user.isVip && goods.vipprice && goods.isvip && user.vipofcentreId.indexOf(user.centreId) != -1) ? goods.vipprice : goods.marketprice,//用户是会员+商品有会员价+商品是会员商品，取会员价
          vipprice: goods.vipprice,
        };
        //多规格

        if(_this.data.showSku && skuData){
          cartItem.total = skuData.selectNum;
          cartItem.skuId = skuData.selectSku.id;
          cartItem.skuTitle = skuData.selectSku.title;
          cartItem.marketprice = (user.isVip && skuData.selectSku.vipprice && goods.isvip) ? skuData.selectSku.vipprice : skuData.selectSku.marketprice;
          cartItem.vipprice = skuData.selectSku.vipprice;
        }

        if (goods.maxbuy && (goods.cartNum + cartItem.total) > goods.maxbuy) {
          wx.showToast({
            title: '已经超过单次购买数量',
            icon: 'none'
          })
          return;
        }

        app.requestUrl({
          method: 'POST',
          url: '/wxapi/cart/add',
          data: cartItem,
        }).then((res) => {
          let index = event.currentTarget.dataset.index  // 获取数据的索引
          let temp = 'goodsList[' + index + '].cartNum'  // 获取goodsList[index].cartNum

          if(_this.data.showSku && skuData){//多规格
            app.globalData.cartTotal += cartItem.total;
            _this.setData({ showSku: false });
          } else {//普通
            if (plus) {//加入购物车
              _this.setData({ [temp]: _this.data.goodsList[index].cartNum + 1 })
              app.globalData.cartTotal += 1;
            } else {//减
              _this.setData({ [temp]: _this.data.goodsList[index].cartNum - 1 })
              app.globalData.cartTotal -= 1;
            }
          }

        })
      }
    },
    //规格加入购物车
    skuAddCart(event){
      if (!this.data.skuGoods.selectSku) {
        wx.showToast({
          title: '请先选择商品规格',
          icon: 'none'
        })
        return;
      }
      let goods = event.currentTarget.dataset.goods;
      if(!goods.selectNum) goods.selectNum = 1;
      let currentTarget = {currentTarget: {dataset: {goods: goods, plus: true, skuData: goods}}};
      this.addCart(currentTarget);
    },

    //改变购物车数量
    onNumChange (event) {
      let goods = event.currentTarget.dataset.goods
      let index = event.currentTarget.dataset.index  // 获取数据的索引

      var num = event.detail - goods.cartNum//num > 0 加；event.detail当前改变值
      let currentTarget = {currentTarget: {dataset: {goods: goods, index: index, plus: (num > 0)}}}
      this.addCart(currentTarget)
    },
    //规格数量
    onNumSkuChange(event){
      let value = event.detail;
      this.setData({
        ['skuGoods.selectNum']: value
      })
    },
    //获取商品数据列表
    getGoodList (isPage, categoryId) {
      if (!isPage) this.setData({currPage: 1})
      let _this = this
      let user = app.getUser();
      let order = '';
      console.log(_this.properties.order);
      if(_this.properties.order == 'true'){
        order = 'desc';
      }else if(_this.properties.order == 'false' && _this.properties.order !== ''){
        order = 'asc';
      }else{
        order = '';
      };
      //商户商品
      if (_this.data.isStationmaster) {
        app.requestUrl({
          method: 'GET',
          url: '/wxapi/product/getProductDataList',
          data: {
            idOrName: _this.properties.keyword,
            pcate: categoryId || '',//分类id
            offset: (_this.data.currPage - 1) * _this.data.perPage,
            limit: _this.data.perPage
          },
          load: 0
        }).then((res) => {
          let tempList = res.data.data.rows
          if (isPage) {//下一页的数据拼接在原有数据后面
            _this.setData({
              goodsList: _this.data.goodsList.concat(tempList)
            })
          }
          else {//第一页数据直接赋值
            _this.setData({
              goodsList: tempList,
              isEmpty: !tempList.length > 0,
              noMore: false,
            })
          }

          //如果返回的数据为空，那么就没有下一页了
          if (tempList.length == 0) _this.setData({noMore: true})
        })
      }
      else {
        let tShopId = app.getShop().id;
        let tCentreId = wx.getStorageSync('tempCentreId');
        app.requestUrl({
          method: 'GET',
          url: '/wxapi/shop/products',
          data: {
            centreId: app.globalData.loginCentreId,
            liansuoid: tShopId ? tShopId : '',//未登录需要传门店id
            teamId: tShopId ? tShopId : '',//未登录需要传门店id
            mid: user.id ? user.id : '',
            isTeam: _this.properties.isTeam ? _this.properties.isTeam : '',
            title: _this.properties.keyword,
            // isKuaidi: _this.properties.express == '1' ? _this.properties.express : '',
            categoryId: categoryId || '',//分类id
            isSpellgroup: _this.properties.isSpellgroup || '',//拼团商品
            ismiaosha: _this.properties.ismiaosha,
            ishot: _this.properties.isHot || '',
            ispresell:_this.properties.isYushou || '',
            isvip: (_this.properties.type === '2') ? '1' : '',
            offset: (_this.data.currPage - 1) * _this.data.perPage,
            limit: _this.data.perPage,
            productType:_this.properties.isYushou ? '1' : (_this.properties.isSpellgroup ? '2' : (_this.properties.ismiaosha ? '3' : (_this.properties.isYuyue ? '4' : '0'))), 
            sidx:_this.properties.sidx,//排序字段，存储选择的是价格还是销量还是最新
            order:order,
            minPrice:_this.properties.minPrice,
            maxPrice:_this.properties.maxPrice,
          },
          load: 0
        }).then((res) => {
          var tempList = res.data.data.rows

          tempList.forEach((item) => {
            item.shouqing = (item.total <= item.salesreal)//商品售罄
            item.timeover = _this.data.serverTime > moment(item.timeend).valueOf()//商品结束
            item.timestartJS = ((_this.data.serverTime < moment(item.timestart).valueOf()) ? true : false)//商品开卖
          })

          if (isPage) {//下一页的数据拼接在原有数据后面
            _this.setData({
              goodsList: _this.data.goodsList.concat(tempList)
            })
          }
          else {//第一页数据直接赋值
            _this.setData({
              goodsList: tempList,
              isEmpty: !tempList.length > 0,
              noMore: false,
            })
          }
          //如果返回的数据为空，那么就没有下一页了
          if (tempList.length == 0) _this.setData({noMore: true})

        })

      }
    },
    bottomList () {
      if (!this.data.noMore) {
        this.setData({
          currPage: this.data.currPage + 1
        })
        this.getGoodList(true)//传true代表进行下一页
      }
    },
    getHeight () {
      //获取屏幕尺寸
      const screenWidth = wx.getSystemInfoSync().windowWidth
      const screenHeight = wx.getSystemInfoSync().windowHeight
      this.setData({
        //获取页面初始状态图片数量，0.63为图片容器的高度值(63vw)，将代码中0.63改为你的容器对应高度
        listIndex: screenHeight / (screenWidth * 0.2),
        screenWidth: screenWidth,
        screenHeight: screenHeight
      })
    },
    // 滚动事件
    cOnPageScroll (e) {
      //滚动距离+屏幕高度换算vw倍数
      let listIndex = (e.scrollTop + this.data.screenHeight) / (this.data.screenWidth * 0.2)
      this.setData({
        listIndex: listIndex
      })
    },

    //规格选择
    skuItemClick(event){
      let skuItem = event.currentTarget.dataset.goods;
      this.setData({
        ['skuGoods.selectSku']: skuItem
      })
    },

    //跳转商品详情
    toGoodItem (event) {
      let user = app.getUser();
      if(user.id == null){
        this.setData({ showLogin: true })
        return;
      }

      let productId = event.currentTarget.dataset.productid
      wx.navigateTo({
        url: '/subIndex/index/good-item/good-item?productId=' + productId
      })
    },

    //跳转添加商品
    toObtainGoods (event) {
      let goods = event.currentTarget.dataset.goods
      wx.navigateTo({
        url: '/sub/user/obtain-goods/obtain-goods?goods=' + JSON.stringify(goods)
      })
    },

    //规格弹框
    showSkuMonitor(){
      let _this = this;
      _this.setData({showSku: !_this.data.showSku})
    },

    //接收登录弹框组件传值
    showLoginFun(event){
      this.setData({
        showLogin: event.detail
      })
    },

    //播放视频
    playVideo(){
      this.setData({ playing: true })
    },
    //播放结束
    endVideo(){
      this.setData({ playing: false })
    },
    //播放错误
    errorVideo(){
      wx.showToast({
        title: '视频播放错误',
        inco: 'none'
      })
      this.setData({ playing: true })
    },
  }
})
